package com.terren.webdig.setting.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.terren.webdig.basic.impl.BasicServiceSupportImpl;
import com.terren.webdig.common.config.ConfigInfo;
import com.terren.webdig.setting.entity.Function;
import com.terren.webdig.setting.entity.LoginUser;
import com.terren.webdig.setting.service.IFunctionService;

@Service("functionService")
public class FunctionServiceImpl extends BasicServiceSupportImpl implements IFunctionService {

	private final String SQL_MAPPER = "setting.functionMapper.";

	public List<Function> getUserFunction(LoginUser loginUser) throws Exception {
		@SuppressWarnings("unchecked")
		List<Function> actionList = (List<Function>) basicDao.findForList(SQL_MAPPER + "getUserFunction", loginUser);
		for (Function oneFunction : actionList) {
			String actionValue = ConfigInfo.ActionValue;// oneFunction.getActionValue();
			String k = oneFunction.getK();
			String actionUrl = actionValue + "?k=" + k;
			oneFunction.setActionUrl(actionUrl);
		}
		return dealFunction(actionList);
	}

	/**
	 * 初始化用户所有功能权限
	 * 
	 * @param loginUser
	 * @param functionList
	 * @throws Exception
	 */
	public void initUserFunction(LoginUser loginUser, List<Function> functionList) throws Exception {
		if (null != functionList) {
			String functionJson = JSON.toJSONString(functionList);
			/** 前台菜单生成 **/
			loginUser.setFunctionJson(functionJson);
			if (!functionList.isEmpty()) {
				for (Function function : functionList) {
					if (!function.getChildren().isEmpty()) {
						Function firstFunction = function.getChildren().get(0);
						loginUser.setFirstFunction(firstFunction);// 初始化用户默认登录的功能
						break;
					}
				}
			}
		}
	}

	/**
	 * 获取权限list 处理成json
	 * 
	 * @param list
	 * @return
	 */
	public List<Function> dealFunction(List<Function> list) {

		// 一级菜单map
		Map<Integer, Function> map = new HashMap<Integer, Function>();
		List<Function> fuList = new ArrayList<Function>(); 
		// 全部遍历 一级菜单都放入 map中
		for (Function functionInfo : list) {
			if (functionInfo.getType() == 0) {
				map.put(functionInfo.getFunctionId(), functionInfo);
			}
		}
		List<Function> childrenList = null;
		for (Function functionInfo : list) {
			int parentId = functionInfo.getParentId();
			if (functionInfo.getType() != 0) {
				Function fun = map.get(parentId);
				functionInfo.setLeaf(true);
				if (fun != null) {
					childrenList = fun.getChildren();
					if (childrenList == null) {
						childrenList = new ArrayList<Function>();
					}
					childrenList.add(functionInfo);
					fun.setChildren(childrenList);
				}
			}
		}
		Set<Entry<Integer, Function>> entrySet = map.entrySet();
		for (Map.Entry<Integer, Function> entry : entrySet) {
			Function functionInfo3 = entry.getValue();
			if (functionInfo3.getChildren() == null) {
				functionInfo3.setChildren(new ArrayList<Function>());
			}
			fuList.add(entry.getValue());
		}
		Collections.sort(fuList, new Comparator<Function>() {

			public int compare(Function o1, Function o2) {
				return o1.getIndex() - o2.getIndex();
			}

		});
		return fuList;
	}

	/**
	 * 获得跳转页面地址
	 * @param sessionUser
	 * @param k
	 * @return
	 */
	public Function getResponseFunction(LoginUser sessionUser, String actionValue, String k,HttpServletRequest request) {
		Function result = null;
		if (k == null) {
			Function firstFunction = sessionUser.getFirstFunction();
			// 默认跳转第一个页面
			if (firstFunction != null) {
				k = firstFunction.getK();
			}
		}
		if (k != null) {
			Map<String, Object> paraMap = new HashMap<String, Object>();

			paraMap.put("actionValue", actionValue);
			paraMap.put("k", k);

			if (sessionUser == null) {
				if (ConfigInfo.ActionValue.equals(actionValue) || ConfigInfo.deActionValue.equals(actionValue)) {
					return null;
				}
			} else {
				int userId = sessionUser.getUserId();
				paraMap.put("userId", userId);
			}

			try {
				if (ConfigInfo.ActionValue.equals(actionValue)) {// 拦截，需要 userId验证
					result = (Function) basicDao.findForObject(SQL_MAPPER + "getFunUrl", paraMap);
				} else if (ConfigInfo.opActionValue.equals(actionValue) || ConfigInfo.deActionValue.equals(actionValue)) {// 不需要userId验证
					result = (Function) basicDao.findForObject(SQL_MAPPER + "getOpenFunUrl", paraMap);
				}
			} catch (Exception e) {
				logger.error("getResponseFunction ERROR", e);
			}
			/** request 中保存 action k **/
			request.setAttribute("functionActionName", actionValue);
			request.setAttribute("functionActionKey", k);
		}
		request.setAttribute("userFunction", result);
		return result;
	}

	// 查询出function列表中的信息
	@SuppressWarnings("unchecked")
	public List<Function> getFunctionQuery(Function function) throws Exception {
		return (List<Function>) basicDao.findForList(SQL_MAPPER + "getFunctionQuery", function);
	}

	// 查询父节点名称的下拉列表
	@SuppressWarnings("unchecked")
	public List<Function> getParentName(Function function) throws Exception {
		return (List<Function>) basicDao.findForList(SQL_MAPPER + "getParentName", function);
	}

	// K值校验
	@SuppressWarnings("unchecked")
	public List<Function> getFunctionK(Function function) throws Exception {
		return (List<Function>) basicDao.findForList(SQL_MAPPER + "getFunctionK", function);
	}


	// 添加功能时，往r_function_parent_child表中插入数据
	public Integer addFunctionZeroParentId(Function function) throws Exception {
		return (Integer) basicDao.save(SQL_MAPPER + "addFunctionZeroParentId", function);
	}

	@SuppressWarnings("unchecked")
	public List<Function> deleteChildParentId(Function function) throws Exception {
		return (List<Function>) basicDao.findForList(SQL_MAPPER + "deleteChild_ParentId", function);
	}

	public Integer updateFunction(Function function) throws Exception {
		return (Integer) basicDao.update(SQL_MAPPER + "updateFunction", function);
	}

	// 删除根据FunctionId删除信息
	@SuppressWarnings("unchecked")
	public List<Function> deletefunction(Function function) throws Exception {
		return (List<Function>) basicDao.findForList(SQL_MAPPER + "deletefunction", function);
	}

	// 获取所有父节点功能
	@SuppressWarnings("unchecked")
	public List<Function> getParentFunctionList(Function function) throws Exception {
		return (List<Function>) basicDao.findForList(SQL_MAPPER + "getParentFunctionList", function);
	}

	// 获取所有子节点功能
	@SuppressWarnings("unchecked")
	public List<Function> getChildFunctionList(Function function) throws Exception {
		return (List<Function>) basicDao.findForList(SQL_MAPPER + "getChildFunctionList", function);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Function> getAllFunction(Function function) throws Exception {
		return (List<Function>) basicDao.findForList(SQL_MAPPER + "getAllFunction", function);
	}

	@Override
	public void addFunction(Function function) throws Exception {
		Integer type = function.getType();
		basicDao.save(SQL_MAPPER + "addFunction", function);
		Function relationFunction = new Function();//u_function_parent_child
		relationFunction.setChildId(function.getFunctionId());
		if(type==0){//一级菜单
			relationFunction.setParentId(0);
		}else if(type==1){//二级菜单
			relationFunction.setParentId(function.getParentId());
		}	
		basicDao.save(SQL_MAPPER + "addFunctionParentIdChildId", relationFunction);
	}
}
